package com.example.imtoken.modules.main.wallet.add_token

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.example.imtoken.core.App
import com.example.imtoken.core.base.BaseViewModel
import com.example.imtoken.core.http.BaseObserver
import com.example.imtoken.core.logic.network.RetrofitUtils
import com.example.imtoken.core.logic.repository.WalletRepository
import com.example.imtoken.entitys.http.CoinsEntity
import com.example.imtoken.entitys.http.CoinsEntityItem
import com.example.imtoken.entitys.http.CreateEntity
import com.example.imtoken.entitys.http.ResponseEntity
import com.example.imtoken.room.base.AppDataBase
import com.example.imtoken.room.schema.AccountSchema
import com.example.imtoken.room.schema.WalletCheckedSchema
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.launch

class AddTokenViewModel(private val repository: WalletRepository) : BaseViewModel() {

    private val coinsLiveData = MutableLiveData<MutableList<CoinsEntityItem>>()

    fun getCoinsData(): MutableLiveData<MutableList<CoinsEntityItem>> {
        return coinsLiveData
    }

    val isSuccess = MutableLiveData(false)

    private val account = AppDataBase.instance.getAccountDao().findOwnerData()

    var addTokenType = 0

    fun getCoins() {
        RetrofitUtils.apiService?.coins()
            ?.subscribeOn(Schedulers.io())
            ?.unsubscribeOn(Schedulers.io())
            ?.subscribe(object : BaseObserver<ResponseEntity<CoinsEntity>>() {
                override fun onSuccess(value: ResponseEntity<CoinsEntity>) {
                    if (value.code == 0) {
                        value.data?.forEach {
                            if (it.coin == "eth") {
                                it.isAddToken = 2
                            }
                        }
                        coinsLiveData.postValue(value.data)
                    } else {
                        mErrorStr.postValue(value.msg)
                    }
                }

                override fun onFailed(e: Throwable) {
                    LogUtils.e(e.message)
                }

            })
    }

    fun getAdminCoins() {
        val accountList = AppDataBase.instance.getAccountDao().findAdminAccount()
        RetrofitUtils.apiService?.coins()
            ?.subscribeOn(Schedulers.io())
            ?.unsubscribeOn(Schedulers.io())
            ?.subscribe(object : BaseObserver<ResponseEntity<CoinsEntity>>() {
                override fun onSuccess(value: ResponseEntity<CoinsEntity>) {
                    if (value.code == 0) {
                        accountList.let { account ->
                            value.data?.let { coins ->
                                for (a in account) {
                                    for (c in coins) {
                                        if (a.coin == c.coin) {
                                            c.isAddToken = 2
                                        }
                                    }
                                }
                            }
                        }
                        coinsLiveData.postValue(value.data)
                    } else {
                        mErrorStr.postValue(value.msg)
                    }
                }

                override fun onFailed(e: Throwable) {
                    LogUtils.e(e.message)
                }

            })
    }

    fun checkedCoin(position: Int) {
        val newData = ArrayList<CoinsEntityItem>()
        coinsLiveData.value?.let {
            for (item in it) {
                val newItem = item.copy()
                newItem.isAddToken = item.isAddToken
                newData.add(newItem)
            }
            if (newData[position].isAddToken == 0) {
                newData[position].isAddToken = 1
            } else if (newData[position].isAddToken == 1) {
                newData[position].isAddToken = 0
            }
            coinsLiveData.value = newData
        }
    }

    fun addWallet() {
        when (addTokenType) {
            0, 2 -> addDefWalletChecked()
        }

        coinsLiveData.value?.let {
            val sb = StringBuffer()
            it.forEach { item ->
                if (item.isAddToken == 1) {
                    if (sb.isEmpty()) {
                        sb.append(item.coin)
                    } else {
                        sb.append(",${item.coin}")
                    }
                }
            }
            if (sb.isEmpty()) {
                isSuccess.postValue(true)
                return
            }
            mDialog.value = true
            viewModelScope.launch {
                try {
                    val createEntity = repository.createUser(
                        sb.toString(),
                        account.password,
                        account.account,
                        account.prompt
                    )
                    repository.addAccountData(
                        createEntity,
                        account.password,
                        account.account,
                        account.prompt
                    )

                    createEntity.forEach { item->
                        addWalletChecked(item.coin?.address)
                    }

                    App.appCode?.let { code ->
                        val bindingWallet = repository.bindingWallet(
                            createEntity[0].coin?.address,
                            account.password,
                            createEntity[0].coin?.coin ?: "eth",
                            code
                        )
                        bindingWallet?.let { LogUtils.json(it) }
                    }
                    mDialog.value = false
                    isSuccess.value = true
                } catch (e: Exception) {
                    mDialog.value = false
                    mErrorStr.value = e.message
                }

            }

//            RetrofitUtils.apiService?.walletCreate(
//                sb.toString(),
//                account.password,
//                account.account,
//                account.prompt
//            )
//                ?.subscribeOn(Schedulers.io())
//                ?.unsubscribeOn(Schedulers.io())
//                ?.subscribe(object : BaseObserver<ResponseEntity<CreateEntity>>() {
//                    override fun onSuccess(value: ResponseEntity<CreateEntity>) {
//                        mDialog.postValue(false)
//                        if (value.code == 0) {
//                            addAccountData(value.data)
//                            isSuccess.postValue(true)
//                        } else {
//                            mErrorStr.postValue(value.msg)
//                        }
//                    }
//
//                    override fun onFailed(e: Throwable) {
//                        mDialog.postValue(false)
//                    }
//
//                })
        }
    }

    private fun addAccountData(createEntity: CreateEntity?) {
        createEntity?.forEach {
            val account = AccountSchema(
                this.account.account,
                this.account.password,
                this.account.prompt,
                it.token,
                it.coin?.address,
                it.coin?.coin,
                it.coin?.mnemonic,
                it.coin?.public_key,
                it.coin?.coin,
                1
            )
            if (AppDataBase.instance.getAccountDao().insertAccount(account) > 0) {
                LogUtils.e("${it.coin?.coin} --->>> 钱包账号添加成功")

                addWalletChecked(it.coin?.address)
            } else {
                LogUtils.e("${it.coin?.coin} --->>> 钱包账号添加失败")
            }
        }
    }

    /**
     * 添加默认选中的钱包
     */
    private fun addDefWalletChecked() {
        coinsLiveData.value?.let {
            it.forEach { item ->
                if (item.isAddToken == 2) {
                    val walletCheckedSchema = WalletCheckedSchema(
                        item.icon,
                        item.coin,
                        item.name,
                        App.createLiveData.value?.coin?.address,
                        item.describe
                    )
                    if (AppDataBase.instance.getWalletCheckedDao()
                            .insertWalletChecked(walletCheckedSchema) > 0
                    ) {
                        LogUtils.e("添加选择-${item.coin}-成功")
                    } else {
                        LogUtils.e("添加选择-${item.coin}-失败")
                    }
                }
            }
        }
    }

    private fun addWalletChecked(address: String?) {
        coinsLiveData.value?.let {
            it.forEach { item ->
                if (item.isAddToken == 1) {
                    val walletCheckedSchema = WalletCheckedSchema(
                        item.icon,
                        item.coin,
                        item.name,
                        address,
                        item.describe
                    )
                    if (AppDataBase.instance.getWalletCheckedDao()
                            .insertWalletChecked(walletCheckedSchema) > 0
                    ) {
                        LogUtils.e("添加选择-${item.coin}-成功")
                    } else {
                        LogUtils.e("添加选择-${item.coin}-失败")
                    }
                }
            }
        }
    }

}